package common

import (
	"flag"
	"net/http"
	"io/ioutil"
	"os"
	"github.com/aws/aws-sdk-go/service/cloudwatch"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/aws"
	"fmt"
)

var (
	RegionFlag = flag.String("region", "cn-north-1", "区域")
)

func HttpGet() (instanceId string, err error) {
	resp, err := http.Get("http://169.254.169.254/latest/meta-data/instance-id")
	if err != nil {
		// handle error
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	instanceId = string(body)
	return
}

func ReadAll(filePth string) ([]byte, error) {
	f, err := os.Open(filePth)
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(f)
}

func MetricDataPut(metricDatum *cloudwatch.MetricDatum,nameSpace string) {
	sess := session.Must(session.NewSession(&aws.Config{
		Region: aws.String(*RegionFlag),
	}))
	svc := cloudwatch.New(sess)

	input := &cloudwatch.PutMetricDataInput{
		Namespace:  aws.String(nameSpace),
		MetricData: []*cloudwatch.MetricDatum{metricDatum},
	}
	out, err := svc.PutMetricData(input)

	if err != nil {
		fmt.Printf("发送监控数据失败 %v\n", err)
	} else {
		fmt.Printf("发送监控数据成功 %v %v\n", *metricDatum.MetricName, *out)
	}
}